﻿/*
 * @Author: Dreamy Icecream 
 * @Date: 2021-01-06 15:00:41 
 * @Description: 深度纹理动态模糊
 * @Last Modified by: Dreamy Icecream
 * @Last Modified time: 2021-01-06 16:59:16
 */

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MotionBlurWithDepthTexture : PostEffectsBase {

	public Shader motionBlurShader;

	private Material motionBlurMaterial = null;
	public Material material {
		get {
			this.motionBlurMaterial = this.CheckShaderAndCreateMaterial (this.motionBlurShader, this.motionBlurMaterial);
			return this.motionBlurMaterial;
		}
	}

	private Camera gameCamera;
	public Camera camera {
		get {
			if (this.gameCamera == null) {
				this.gameCamera = this.GetComponent<Camera> ();
			}
			return this.gameCamera;
		}
	}

	/** 模糊图像大小 */
	[Range (0.0f, 1.0f)]
	public float blurSize = 0.5f;

	/** 上一帧的视角*投影矩阵 */
	private Matrix4x4 previousViewProjectMatrix;

	private void OnEnable () {
		this.camera.depthTextureMode |= DepthTextureMode.Depth;
	}

	private void OnRenderImage (RenderTexture src, RenderTexture dest) {
		if (this.material != null) {

			this.material.SetFloat ("_BlurSize", this.blurSize);
			this.material.SetMatrix ("_PreviousViewProjectionMatrix", this.previousViewProjectMatrix);

			Matrix4x4 currentViewProjectionMatrix = this.camera.projectionMatrix * this.camera.worldToCameraMatrix;
			Matrix4x4 currentViewProjectionInverseMatrix = currentViewProjectionMatrix.inverse;

			this.material.SetMatrix ("_CurrentViewProjectionInverseMatrix", currentViewProjectionInverseMatrix);

			this.previousViewProjectMatrix = currentViewProjectionMatrix;

			Graphics.Blit (src, dest, this.material);

		} else {
			Graphics.Blit (src, dest);
		}
	}

}